package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.service.ArticleCollectionService;
import com.heima.article.thread.AppThreadLocalUtil;
import com.heima.common.cache.CacheService;
import com.heima.common.constants.BehaviorConstants;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author itheima
 * @since 2022-07-20
 */
@Service
public class ArticleCollectionServiceImpl implements ArticleCollectionService {

    @Autowired
    private CacheService cacheService;

    @Override
    public ResponseResult collection(CollectionBehaviorDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        Integer userId = user.getId();

        Short type = dto.getType();
        Long entryId = dto.getEntryId();

        // 收藏
        if (0 == type) {
            Object o = cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + entryId, userId.toString());
            if (o != null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "已收藏");
            }

            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + entryId, userId.toString(), JSON.toJSONString(dto));
        }
        // 取消收藏
        else if (1 == type) {
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + entryId, userId.toString());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}